// 数据库相关操作
const mysql = require('mysql2/promise')
const config = require('../config')
// 线程池（连接池）
const pool = mysql.createPool({
    host: config.db.host,
    port: config.db.port,
    user: config.db.user,
    password: config.db.password,
    database: config.db.database
})
// 执行sql的方法
const allServices = {
    async query(sql, values) {
        try{
             //通过连接词连接myspl
        const conn = await pool.getConnection()//连接数据库异步
        // 执行各种增删改查的sql语句
        const [rows, fields] = await conn.query(sql, values) //这两个query是不一样的 上面的query随便叫
        // 释放连接
        pool.releaseConnection(conn)
        //返回查询结果
        return  Promise.resolve(rows)
        }catch(error){  
            return Promise.reject(error)
        }
    }
}
//登录要执行的函数
const userLogin=(username,password)=>{
    let _sql=`select*from user where username="${username}"and password="${password}";`
     return allServices.query(_sql)
}
//查找账号是否存在
const userFind=(username)=>{
    let _sql=`select*from user where username="${username}";`
    return allServices.query(_sql)
}
//数据库写入
const userRegister=(data)=>{
    let _sql=`insert into user set username="${data.username}",password="${data.password}",nickname="${data.nickname}",create_time="${data.create_time}";`
    return allServices.query(_sql)
}
//根据类型查找宠物数据
const findPetListBytype=(pet_type)=>{
    let _sql=`select*from pet where pet_type="${pet_type}";`
    return allServices.query(_sql)
}
//发布内容
const publishPet=(data)=>{
    let _sql=`insert into pet set pet_content="${data.pet_content}",pet_img="${data.pet_img}",pet_type="${data.pet_type}",pet_breed="${data.pet_breed}",pet_contact="${data.pet_contact}",pet_feature="${data.pet_feature}",update_time="${data.update_time}",create_time="${data.create_time}";`
    return allServices.query(_sql)
}



module.exports={
    userLogin,
    userFind,
    userRegister,
    findPetListBytype,
    publishPet
}









